package com.hps.activemq.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.hps.activemq.entity.Good;
import com.hps.activemq.entity.Order;
import com.hps.activemq.mapper.GoodMapper;
import com.hps.activemq.mapper.OrderMapper;
import com.hps.activemq.service.OrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2019-01-11
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    private GoodMapper goodMapper;

    public OrderServiceImpl(GoodMapper goodMapper) {
        this.goodMapper = goodMapper;
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public Map<String, Object> checkSuccess(Long userId, Long goodId) {
        Map<String, Object> result = Maps.newHashMap();
        EntityWrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId).eq("good_id", goodId);
        int count = selectCount(wrapper);
        if (count >  0) {
            result.put("success", true);
        } else {
            result.put("success", false);
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void dealOrder(Order order) {
        logger.info("开始处理订单...");
        Map<String, Object> map = Maps.newHashMap();
        map.put("user_id", order.getUserId());
        map.put("good_id", order.getGoodId());
        List<Order> orders = selectByMap(map);
        if (CollectionUtils.isEmpty(orders)) {
            // 将库存减1
            int result = goodMapper.updateStock(order.getGoodId());
            if (result > 0) {
                // 保存订单
                insert(order);
            }
            logger.info("订单处理成功...");
        }
    }
}
